package com.example.app3_1;

import static androidx.constraintlayout.helper.widget.MotionEffect.TAG;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

public class LoginActivity extends AppCompatActivity {

    private EditText etUsername;
    private EditText etPassword;
    private CheckBox cbAgreement;
    private CheckBox cbAutoLogin;
    private Button btnLogin;
    private TextView tvLoading;
    private ProgressBar progressBar;
    private AuthViewModel authViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d(TAG, "onCreate");

        // 测试：登录前切换网络应该没有提示
        Log.d(TAG, "当前在登录页，网络切换不会有提示");

        // 初始化ViewModel
        authViewModel = new ViewModelProvider(this).get(AuthViewModel.class);

        // 初始化视图
        etUsername = findViewById(R.id.et_username);
        etPassword = findViewById(R.id.et_password);
        cbAgreement = findViewById(R.id.cb_agreement);
        cbAutoLogin = findViewById(R.id.cb_auto_login);
        btnLogin = findViewById(R.id.btn_login);
        progressBar = findViewById(R.id.progress_loading);
        tvLoading = findViewById(R.id.tv_loading);

        // 设置登录按钮初始状态为灰色
        setLoginButtonState(false);

        // 检查自动登录
        if (authViewModel.isAutoLoginEnabled()) {
            performAutoLogin();
        }

        // 观察登录结果
        authViewModel.getLoginResult().observe(this, result -> {
            progressBar.setVisibility(View.GONE);
            tvLoading.setVisibility(View.GONE);

            if ("success".equals(result)) {
                Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                String username = etUsername.getText().toString().trim();
                Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
                intent.putExtra("username", username);
                startActivity(intent);
                finish();
            } else if (result.startsWith("error:")) {
                String errorMsg = result.substring(6);
                Toast.makeText(LoginActivity.this, "登录失败: " + errorMsg, Toast.LENGTH_SHORT).show();
            }
        });

        // 观察注册结果
        authViewModel.getRegisterResult().observe(this, result -> {
            progressBar.setVisibility(View.GONE);
            tvLoading.setVisibility(View.GONE);

            if ("success".equals(result)) {
                Toast.makeText(LoginActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                String username = etUsername.getText().toString().trim();
                Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
                intent.putExtra("username", username);
                startActivity(intent);
                finish();
            } else if (result.startsWith("error:")) {
                String errorMsg = result.substring(6);
                Toast.makeText(LoginActivity.this, "注册失败: " + errorMsg, Toast.LENGTH_SHORT).show();
            }
        });

        // 观察自动登录结果
        authViewModel.getAutoLoginResult().observe(this, result -> {
            progressBar.setVisibility(View.GONE);
            tvLoading.setVisibility(View.GONE);

            if ("success".equals(result)) {
                Toast.makeText(LoginActivity.this, "自动登录成功", Toast.LENGTH_SHORT).show();
                String savedEmail = getSharedPreferences("UserData", 0).getString("autoLoginEmail", "用户");
                Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
                intent.putExtra("username", savedEmail);
                startActivity(intent);
                finish();
            } else if (result.startsWith("error:")) {
                String errorMsg = result.substring(6);
                // 自动登录失败，不显示提示，直接显示登录页面
                Log.d(TAG, "自动登录失败: " + errorMsg);
            }
        });

        // 用户名输入框焦点变化监听
        etUsername.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    // 获取焦点时边框变亮
                    etUsername.setBackgroundColor(Color.parseColor("#E3F2FD"));
                } else {
                    // 失去焦点时恢复默认（透明）
                    etUsername.setBackgroundColor(Color.TRANSPARENT);
                    // 去掉前后空格
                    String text = etUsername.getText().toString().trim();
                    etUsername.setText(text);
                }
            }
        });

        // 密码输入框焦点变化监听
        etPassword.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    // 获取焦点时边框变亮
                    etPassword.setBackgroundColor(Color.parseColor("#E3F2FD"));
                } else {
                    // 失去焦点时恢复默认
                    etPassword.setBackgroundColor(Color.TRANSPARENT);
                }
            }
        });

        // 协议勾选框状态变化监听
        cbAgreement.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // 更新登录按钮状态
                setLoginButtonState(isChecked);
            }
        });

        // 登录按钮点击事件
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取输入的用户名和密码
                String username = etUsername.getText().toString().trim();
                String password = etPassword.getText().toString();
                boolean rememberMe = cbAutoLogin.isChecked();

                // 检查用户名是否为空
                if (username.isEmpty()) {
                    Toast.makeText(LoginActivity.this, "请输入账号", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 检查密码是否为空
                if (password.isEmpty()) {
                    Toast.makeText(LoginActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 检查是否同意协议
                if (!cbAgreement.isChecked()) {
                    Toast.makeText(LoginActivity.this, "请同意用户协议", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 显示进度条
                progressBar.setVisibility(View.VISIBLE);
                tvLoading.setVisibility(View.VISIBLE);
                tvLoading.setText("正在登录中...");

                // 执行登录
                authViewModel.login(username, password, rememberMe);
            }
        });

        // 注册文本点击事件
        // LoginActivity.java - 修改注册点击事件
        findViewById(R.id.tv_register).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = etUsername.getText().toString().trim();
                String password = etPassword.getText().toString();

                if (username.isEmpty() || password.isEmpty()) {
                    Toast.makeText(LoginActivity.this, "请输入账号和密码", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (!cbAgreement.isChecked()) {
                    Toast.makeText(LoginActivity.this, "请同意用户协议", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 显示进度条
                progressBar.setVisibility(View.VISIBLE);
                tvLoading.setVisibility(View.VISIBLE);
                tvLoading.setText("正在注册中...");

                // 执行注册，不传递自动登录状态
                authViewModel.register(username, password);
            }
        });
        if (shouldAutoLogin()) {
            performAutoLogin();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d(TAG, "onRestart");
    }

    // 设置登录按钮外观的方法
    private void setLoginButtonState(boolean isAgreed) {
        if (isAgreed) {
            // 勾选协议时，按钮变为正常状态
            btnLogin.setBackgroundColor(Color.parseColor("#6200EE"));
            btnLogin.setTextColor(Color.WHITE);
        } else {
            // 未勾选协议时，按钮变为灰色
            btnLogin.setBackgroundColor(Color.parseColor("#CCCCCC"));
            btnLogin.setTextColor(Color.parseColor("#666666"));
        }
    }
    // LoginActivity.java - 完善自动登录检查
    private boolean shouldAutoLogin() {
        SharedPreferences prefs = getSharedPreferences("UserData", 0);
        boolean autoLoginEnabled = prefs.getBoolean("autoLoginEnabled", false);
        String autoLoginToken = prefs.getString("autoLoginToken", "");

        // 只有明确启用了自动登录且有有效token时才执行自动登录
        return autoLoginEnabled && !autoLoginToken.isEmpty();
    }
    private void performAutoLogin() {
        progressBar.setVisibility(View.VISIBLE);
        tvLoading.setVisibility(View.VISIBLE);
        tvLoading.setText("自动登录中...");
        authViewModel.autoLogin();
    }
}